package com.xpgk.dto;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;


import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
import com.xpgk.excel.ExcelUtil;

public class XlsRender extends Render {

	private static final String CONTENT_TYPE = "application/msexcel;charset=UTF-8";

	private final List<Record> data;
	private final String[] headers;
	private final String[] columns;
	private final String fileName;

	public XlsRender(List<Record> data, String[] headers, String[] columns, String fileName) {
		this.data = data;
		this.headers = headers;
		this.columns = columns;
		this.fileName = fileName + ".xls";
	}

	@Override
	public void render() {
		this.response.reset();
	    try {
			this.response.setHeader("Content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(this.fileName,"UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
	    this.response.setContentType(CONTENT_TYPE);
	    OutputStream os = null;
	    try {
	      os = this.response.getOutputStream();
	      ExcelUtil.createExcel(os, this.data, this.headers, this.columns);
	    } catch (Exception e) {
	      throw new RenderException(e);
	    } finally {
	      try {
	        if (os != null) {
	          os.flush();
	          os.close();
	        }
	      } catch (IOException e) {
	        LogKit.error(e.getMessage(), e);
	      }
	    }
	}

}
